import sun.print.PSStreamPrintService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * Created by dllo on 18/5/14.
 */
@WebServlet(name = "SearchServlet", urlPatterns = "/search")
public class SearchServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");

        // 获取前端传过来的参数
        String key = request.getParameter("key");


        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            Properties properties = new Properties();
            //使用类名.class.getClassLoader()
            //获取 类加载器
            //类加载器的getResourceAsStream
            //是相对于src路径下的
            InputStream is = SearchServlet.class.getClassLoader().getResourceAsStream("JDBC.properties");
            properties.load(is);

            // 创建连接
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lanou_news", properties);

            // 预编译
            String sql = "SELECT * FROM my_news WHERE title like ?";
            PreparedStatement statement = conn.prepareStatement(sql);

            // 设置参数
            statement.setString(1, "%" + key + "%");

            // 获得查询结果
            ResultSet rs = statement.executeQuery();

            // 输出查询结果
            PrintWriter pw = response.getWriter();

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                pw.println(id + "-" + title);
                pw.println("<br/>");
            }

            rs.close();
            statement.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
